package com.cheng.system.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cheng.common.exception.CustomException;
import com.cheng.system.model.User;
import com.cheng.system.service.IAuthService;
import com.cheng.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthUsernamePasswordImpl implements IAuthService<User> {
    @Autowired
    UserService userService;
    @Override
    public SaTokenInfo signUp(User user) throws Throwable {

        User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName()));
        if (one != null) {
            throw new CustomException("用户已存在");
        }
        user.setNickName("新用户");
        user.setPassword(SecureUtil.md5(user.getUserName() + user.getPassword()));
        userService.save(user);
        StpUtil.login(user.getUserId());
        return  StpUtil.getTokenInfo();


    }

    @Override
    public SaTokenInfo login(User user) throws Throwable {
        User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName()));
        if (one == null) {
            throw new CustomException("用户不存在");
        }
        String md5Password = SecureUtil.md5(user.getUserName() + user.getPassword());
        if (!md5Password.equals(one.getPassword())) {
            throw new CustomException("账号或密码错误");
        }
        StpUtil.login(one.getUserId());
        return StpUtil.getTokenInfo();
    }
}
